var http  =  require('http');
var sys   =  require('util');
var fs    =  require('fs');
var parse =  require('./parse');
var zlib  =  require('zlib');
var url   =  require('url');
var querystring=require('querystring');
var path = require('path');

var MainAddress = '';
var request = require('request');

var RESENUM =
{
	DOCWRITE :0 , 
	DOCURL:1,
	DOCLOC:2,
	DOCREF:3,
	EVAL:4,
	WOPEN:5,
	INELM:6
};
	
function generateGraph(req, res, analysis, address)
{
   var page = 
"<html>"+
 "  <head>"+
 "<title>URL Analyzer - Esfandiar Manii - Russel Fritch - Richie Steigerwald</title>"+
  "   <script type=\"text/javascript\" src=\"https://www.google.com/jsapi\"></script>"+
  "   <script type=\"text/javascript\">"+
  "     google.load(\"visualization\", \"1\", {packages:[\"corechart\"]});"+
  "     google.setOnLoadCallback(drawChart);"+
  "     function drawChart() {"+
  "       var data = google.visualization.arrayToDataTable(["+
  "         ['Task', 'Hours per Day'],";
  page +=  "['Total Number of Scripts'," +analysis[0].toString()+"],";
  page +=  "['Phishing Scripts'," +analysis[1].toString()+"],";
  page +=  "['Document Write'," +analysis[2][RESENUM.DOCWRITE].toString()+"],";
  page +=  "['Document URL'," +analysis[2][RESENUM.DOCURL].toString()+"],";
  page +=  "['Document Location'," +analysis[2][RESENUM.DOCLOC].toString()+"],";
  page +=  "['Document Referrer'," +analysis[2][RESENUM.DOCREF].toString()+"],";
  page +=  "['Evaluations'," +analysis[2][RESENUM.EVAL].toString()+"],";
  page +=  "['Window Open'," +analysis[2][RESENUM.WOPEN].toString()+"],";
  page +=  "['Inner HTML'," +analysis[2][RESENUM.INELM].toString()+"]";
  page +=  "       ]);"+

  "       var options = {"+
  "         title: 'Analysis of the URL: "+address.toString()+"'"+
  "        ,backgroundColor: { fill:'transparent' } "+
  "      };"+


"         var chart = new google.visualization.PieChart(document.getElementById('chart_div'));"+
"         chart.draw(data, options);"+
"       }"+
"     </script>"+
"   </head>"+
"   <body style=\"text-align:center; background-image:url(images/body_bg.gif);\">"+
"     "+
"        <div style=\"text-align:center\"> <div id=\"chart_div\" style=\"width: 100%; height: 400px;\"></div><p>Do you want to continue? <input type=\"submit\" value=\"Continue\" onClick=\"parent.location='"+MainAddress+"'\" /></p> </div>"+
"   </body>"+
" </html>";
res.end(page);
MainAddress = '';
}

function extractJs(data)
{
	
	//Find all script tags
	var results = data.match(/<script[^>]*>([\s\S]*?)<\/script>/gi);
	var srcS = data.match(/<script[^>]*src=(\'|")(.+?)\1[^>]*?>/gi);
		
	if(srcS != null)
	{
		for(var i = 0; i < srcS.length; i++)
		{
			var tmp = srcS[i].match(/src=(\'|")(.+?)\1[^>]*?/gi);	
			tmp = tmp[0];
			tmp = tmp.replace("src=", '');
			if(tmp[0] == '\"' || tmp[1] == '\'')
			{
				tmp = tmp.substring(1, tmp.length-1);
			}
		}
	}	

	var ableCounter = results.length;
	var tmpResults = new Array(0,0,0,0,0,0,0);
	var arrResults = new Array(0,0,0,0,0,0,0);
	var finalSetup = new Array(0,0,0,0,0,0,0);
	
	if(results != null) {
		for(var i=0; i<results.length; i++) 
		{
			console.log("-------- " + i.toString() + "----------------");
		
			//Remove script tags
			results[i] = results[i].replace(/<script[^>]*>/gi, '');
			results[i] = results[i].replace(/<\/script>/gi, '');
			results[i] = results[i].replace(/<!--/gi, '');
			results[i] = results[i].replace(/-->/gi, '');
		     
			try
			{
				tmpResults = parse.parseString(results[i]);
				console.log("Parsed " +tmpResults);
				for(var j = 0; j < tmpResults.length; j++)
					arrResults[j] += tmpResults[j];
			
			}
			catch(e)
			{
				console.log(results[i]);
				console.log("Unable to Parse Script" + e.toString());
				ableCounter--;
			}

		}
	}
        var str = fs.readFileSync('setup.ps').toString();      
        var splitted = str.split('\n');

        for(i = 0; i < splitted.length; i++)
        {
           if(splitted[i] == 'XScript')
	   {
		finalSetup[0] = arrResults[0];
		finalSetup[1] = arrResults[1];
		finalSetup[2] = arrResults[2];
           }
	   if(splitted[i] == 'Client')
	   {
		finalSetup[3] = arrResults[3];
		finalSetup[4] = arrResults[4];
           }

	   if(splitted[i] == 'Stored')
	   {
		finalSetup[5] = arrResults[5];
		finalSetup[6] = arrResults[6];
           }
        }
        console.log(splitted);
	console.log(arrResults);
	//Return results.length, ableCounter, arrResults
	var retu = new Array(results.length, results.length - ableCounter, finalSetup);
   
        return retu;
}

http.createServer(function(request, response) 
{
  if (url.parse(request.url).pathname.indexOf("/Agree") != -1)
  {
      var index = request.url.indexOf("/Agree");
      var str = request.url.substring(index+7);
      var t = querystring.parse(str);
      enterAgree(request, response, t.address);
  }

  else {

    var filePath = '.' + request.url;
    
    if (filePath == './')
        filePath = './index1.html';
         
    var extname = path.extname(filePath);
    var contentType = 'text/html';
    switch (extname) {
        case '.js':
            contentType = 'text/javascript';
            break;
        case '.css':
            contentType = 'text/css';
            break;
    }

    path.exists(filePath, function(exists) {
     
        if (exists) {
            fs.readFile(filePath, function(error, content) {
                if (error) {
                    response.writeHead(500);
                    response.end();
                }
                else {
                    response.writeHead(200, { 'Content-Type': contentType });
                    response.end(content, 'utf-8');
                }
            });
        }
        else {
            response.writeHead(404);
            response.end();
        }
    });

  }

}).listen(8080, '127.0.0.1');

function enterAgree(req, res, url)
{
   if(url != '')
      analyzeIt(req, res, url)

   else {
	if(MainAddress == '') {
	      res.write('Invalid URL');
      	      res.end();
	}
	else
	{
		analyzeIt(req, res, MainAddress)	
	}
    }
	
     
}

function analyzeIt(req, res, analyzeIt)
{
  console.log(analyzeIt);
  var requestedUri = analyzeIt;
  MainAddress = analyzeIt;
 
  request({ uri:analyzeIt.toString() }, function (error, response, body) {
  if (error && response.statusCode !== 200) {
    console.log('Error when contacting google.com')
  }

  // Print the google web page.
  var analysisResults = extractJs(body.toString());
  console.log(analysisResults);
  generateGraph(req, res, analysisResults, analyzeIt);
  
  });	    	
}
